﻿using _网易云.Model;
using _网易云.Utility;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _网易云
{
    /// <summary>
    /// 
    /// </summary>
    //[Obsolete("使用NetEaseProvider会更好的")]
    public class PlayListSearch
    {
        private static Logger logger = new Logger(typeof(PlayListSearch));
        public static List<PlayList> Crawler(string url)
        {
            List<PlayList> palyLists = new List<PlayList>();
            try
            {
                string html = HttpHelper.DownloadPalyList(url);

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                string fristPath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' u-cover')]";
                HtmlNodeCollection nodeList = doc.DocumentNode.SelectNodes(fristPath);
                foreach (HtmlNode node in nodeList)
                {
                    palyLists.Add(GetPalyList(node.InnerHtml));
                }
            }
            catch (Exception ex)
            {

                logger.Error("CrawlerMuti出现异常", ex);
            }
            return palyLists;
        }
        private static PlayList GetPalyList(string innerHtml)
        {
            string path = "//a";
            string imagePath = "//img";
            //string imagePath2 = "//img/@data-src";
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(innerHtml);
            HtmlNodeCollection nodeList = doc.DocumentNode.SelectNodes(path);
            HtmlNodeCollection imgNodeList = doc.DocumentNode.SelectNodes(imagePath);
            HtmlNode node = nodeList.FirstOrDefault();
            HtmlNode imgNode = imgNodeList.FirstOrDefault();
            PlayList palyList = new PlayList();
            palyList.Url = node.Attributes["href"].Value;
            palyList.Title = node.Attributes["title"].Value;
            if (node.Attributes.Count > 3)
            {
                palyList.Id = node.Attributes["data-res-id"].Value;
                palyList.ImageUrl = imgNode.Attributes["src"].Value;
            }
            else
            {
                palyList.ImageUrl = imgNode.Attributes["data-src"].Value;
            }
     


            return palyList;
        }

    }
}
